package com.qall.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class InvokeUtil {
    /**
     * @param methodName 方法名称
     * @param paramsType 参数类型
     * @param params     参数
     * @param instance   被调用的对象
     * @return 调用结果
     */
    public static String invokeMethod(String methodName, String[] paramsType, String[] params, Object instance) {
        String ret = "";
        try {
            int paramsLength = params.length;
            Class<?> tClass =instance.getClass();
            tClass.newInstance();
            Class<?>[] paramsTypeClass = new Class[paramsLength];
            for (int i = 0; i < paramsLength; i++) {
                paramsTypeClass[i] = Class.forName(paramsType[i]);
            }
            Object[] paramsObject = new Object[paramsLength];
            for (int i = 0; i < paramsLength; i++) {
                paramsObject[i] = JSONUtil.fromJson(params[i], paramsTypeClass[i]);
            }
            Method method = tClass.getMethod(methodName, paramsTypeClass);
            Object retObj = method.invoke(instance, paramsObject);
            ret = JSONUtil.toJson(retObj);
            return ret;
        } catch (ClassNotFoundException | InstantiationException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return "";
    }

}
